package com.badibadi.mail;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.badibadi.activity.BaseActivity;
import com.badibadi.activity.MyDataActivity;
import com.badibadi.activity.SeeOtherPeopleSpaceActivity;
import com.badibadi.adapter.GridViewListAdapter;
import com.badibadi.infos.PayUserContactShow1Model;
import com.badibadi.mytools.CalendarTools;
import com.badibadi.mytools.CommonUtils;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.HtmlUtils;
import com.badibadi.mytools.RegexUtils;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.AcceptClubMailActivity;
import com.badibadi.uniclubber.R;
import com.badibadi.uniclubber.R.id;
import com.badibadi.uniclubber.R.layout;
import com.libjph.util.StringUtil;
import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 另一个一个是Mail15_huifuActivity 答方收到问方的消息后设定一个咨询费给问方，等待问方同意(这个界面设定质询费) -1
 * 
 * @author Administrator 网络连接出错
 * 
 * 
 *         答方：设定一个咨询费 问方：等待答方设定 设定完成后：转到Mail67Activity（等待问方同意该质询费） L_adapter
 *         contents
 */
public class Mail245Activity extends BaseActivity {//time
	// 匿名头像地址
	public String nimingHead = Constants.BadiDownImgUrl
			+ "/Public/Uploads/1.png" + Constants.appPhoto4img;
	public static final String TAG = "Mailtest";
	Button return_btn;
	ImageView delete;

	Button shedingzhixunfei;
	private AlertDialog al_delete, al_sheding;
	String feiyong;
	private DisplayImageOptions options;
	public PayUserContactShow1Model payUserContactShow1Model;
	public String rank;// (用于删除)操作这身份；(确定是答方还是问方) ---操作者的身份 asker：问方 answerer：答方
						// 注意：当为“用户联系”才有该参数
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.l_net_error));
				} catch (Exception e) {
				}
				break;
			case 2:// 设定成功
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					// initListView();
					// initView();
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.wx_set_success));
					Intent intent = new Intent(Mail245Activity.this,
							Mail67Activity.class);
					// payUserContactShow1Model.getZhannei_usercontact().get(0).setIs_fee("1");
					payUserContactShow1Model.getZhannei_usercontact().get(0)
							.setFees(feiyong);
					intent.putExtra("payUserContactShow1Model",
							payUserContactShow1Model);
					startActivity(intent);
					finish();

				} catch (Exception e) {
				}
				break;
			case 3:
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.l_xb12));
				} catch (Exception e) {
				}
				break;
			case 4:// 系统错误
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.l_xb12));
				} catch (Exception e) {
				}
				break;
			case 5:// 删除站内信成功
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.wx_delete_success));
					Constants.is_shuaxin = true;
					finish();
				} catch (Exception e) {
				}
				break;
			case 6:// 删除站内信成功
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.wx_delete_false));
				} catch (Exception e) {
				}

				break;
			case 7:// 设置咨询费失败
				Utils.ExitPrgress(Mail245Activity.this);
				try {
					Utils.showMessage(Mail245Activity.this, getResources()
							.getString(R.string.wx_set_false));
				} catch (Exception e) {
				}

				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		goToTheTitle();
		setContentView(R.layout.activity_mail245);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();

		payUserContactShow1Model = (PayUserContactShow1Model) getIntent()
				.getSerializableExtra("payUserContactShow1Model");
		if (payUserContactShow1Model.getUid().equals(
				Utils.getUid(Mail245Activity.this))) {
			rank = "answerer";// 我是答方
		} else {
			rank = "asker";
		}
		PeiZhi();
		DongTaiPeiZhi();
	}

	protected void DongTaiPeiZhi() {
		// TODO Auto-generated method stub
		// 设定质询费
		Button shedingzhixunfei = (Button) this
				.findViewById(R.id.shedingzhixunfei);
		if (payUserContactShow1Model.getUid().equals(
				Utils.getUid(Mail245Activity.this))) {
			shedingzhixunfei.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// setFees(); quxiao
					LayoutInflater inflater = LayoutInflater
							.from(Mail245Activity.this);
					View view = inflater
							.inflate(R.layout.shedingzixunfei, null);

					// 支付宝手续费
					TextView alipay_charge = (TextView) view
							.findViewById(R.id.alipay_charge);
					alipay_charge.setText(payUserContactShow1Model
							.getAlipay_charge());
					// 达人
					TextView expert_charge = (TextView) view
							.findViewById(R.id.expert_charge);
					expert_charge.setText(payUserContactShow1Model
							.getExpert_charge());
					// 一般用户
					TextView member_charge = (TextView) view
							.findViewById(R.id.member_charge);
					member_charge.setText(payUserContactShow1Model
							.getMember_charge());
					// 最低咨询费
					TextView lowest_fee = (TextView) view
							.findViewById(R.id.lowest_fee);
					lowest_fee.setText(payUserContactShow1Model.getLowest_fee());
					//
					TextView replay_limit_time = (TextView) view
							.findViewById(R.id.replay_limit_time);
					replay_limit_time.setText(""
							+ payUserContactShow1Model.getReplay_limit_time());
					final EditText et_feiyong = (EditText) view
							.findViewById(R.id.et_feiyong);
					// et_feiyong.setText();

					// 确定
					Button queding = (Button) view.findViewById(R.id.queding);
					queding.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (et_feiyong.getText().toString().equals("")) {
								Utils.showMessage(
										Mail245Activity.this,
										getResources().getString(
												R.string.wx_txt_84));
							} else if (Double.parseDouble(et_feiyong.getText()
									.toString()) < Double
									.parseDouble(payUserContactShow1Model
											.getLowest_fee())) {
								Utils.showMessage(
										Mail245Activity.this,
										getResources().getString(
												R.string.wx_txt_85)
												+ payUserContactShow1Model
														.getLowest_fee()
												+ "RMB");
							} else {
								feiyong = et_feiyong.getText().toString();
								setFees(feiyong);
							}

						}
					});
					Button quxiao = (Button) view.findViewById(R.id.quxiao);
					quxiao.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (al_sheding != null)
								al_sheding.dismiss();
						}
					});
					al_sheding = new AlertDialog.Builder(Mail245Activity.this)
							.setView(view).show();
				}
			});
			shedingzhixunfei.setVisibility(View.VISIBLE);
		} else {
			shedingzhixunfei.setVisibility(View.GONE);
		}
	}

	private void PeiZhi() {
		Constants.is_shuaxin = false;
		this.findViewById(R.id.return_btn).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});
		// 主旨
		TextView title = (TextView) this.findViewById(R.id.title);
		title.setText(""
				+ payUserContactShow1Model.getZhannei_usercontact().get(0)
						.getTitle());

		// 寄件者
		TextView jijianfang = (TextView) this.findViewById(R.id.jijianfang);
		if (payUserContactShow1Model.getSender().getNickName().equals("-1")) {
			jijianfang.setText(getResources().getString(
					R.string.wx_Anonymous_user));
		} else {
			jijianfang.setText(""
					+ payUserContactShow1Model.getSender().getNickName());
			jijianfang.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (payUserContactShow1Model != null) {
						String uud = ""
								+ payUserContactShow1Model.getSender().getId();
						if (uud.equals("" + Utils.getUid(Mail245Activity.this))) {
							Intent intent = new Intent(Mail245Activity.this,
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(Mail245Activity.this,
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", uud);
							startActivity(intent);
						}

					}
				}
			});
		}

		// 收件者
		TextView shoujianfang = (TextView) this.findViewById(R.id.shoujianfang);
		if (payUserContactShow1Model.getReceiver().getNickName() != null) {

			if (payUserContactShow1Model.getReceiver().getNickName()
					.equals("-1")) {
				shoujianfang.setText(getResources().getString(
						R.string.wx_Anonymous_user));
			} else {
				shoujianfang.setText(""
						+ payUserContactShow1Model.getReceiver().getNickName());
			}

			shoujianfang.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (payUserContactShow1Model != null) {
						String uud = payUserContactShow1Model.getReceiver()
								.getId();
						if (uud.equals("" + Utils.getUid(Mail245Activity.this))) {
							Intent intent = new Intent(Mail245Activity.this,
									MyDataActivity.class);
							startActivity(intent);
						} else {
							Intent intent = new Intent(Mail245Activity.this,
									SeeOtherPeopleSpaceActivity.class);
							intent.putExtra("friend_id", uud);
							startActivity(intent);
						}

					}
				}
			});
		}
		try {
			// //内容
			// TextView contents=(TextView)this.findViewById(R.id.contents);
			//
			// new HtmlUtils(this, contents,
			// ""+payUserContactShow1Model.getZhannei_usercontact().get(0).getContents()).showTextView();

			ListView L_adapter = (ListView) this.findViewById(R.id.L_adapter);
			ListAdapter adapter = new ListAdapter();
			L_adapter.setAdapter(adapter);

		} catch (Exception e) {
		}
		// 发送时间
		TextView time = (TextView) this.findViewById(R.id.time);
		String t = payUserContactShow1Model.getZhannei_usercontact().get(0)
				.getTime();
		String tim = CalendarTools.getFormatTime(
				Double.parseDouble((t + "000")), "yyyy/MM/dd hh:mm");
//		LogUtils.d("tim="+tim+"t="+t);
		time.setText(tim);
		// 删除
		ImageView delete = (ImageView) this.findViewById(R.id.delete);
		delete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				LayoutInflater inflater = LayoutInflater
						.from(Mail245Activity.this);
				View view = inflater.inflate(R.layout.quedingshanchucixinjian,
						null);
				view.findViewById(R.id.queding).setOnClickListener(
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								delete(Utils.getUid(Mail245Activity.this),
										payUserContactShow1Model
												.getZhannei_Id(),
										"zhannei_usercontact", rank, handler);
							}
						});
				view.findViewById(R.id.quxiao).setOnClickListener(
						new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								if (al_delete != null)
									al_delete.dismiss();
							}
						});
				al_delete = new AlertDialog.Builder(Mail245Activity.this)
						.setView(view).show();
			}
		});

	}

	/**
	 * 有咨询费，答方设定咨询费操作---POST
	 * 
	 * @param $zhaneniId
	 *            站内信ID
	 * @param $uid
	 *            登录用户（答方）
	 * @param $fees
	 *            设定的问题咨询费
	 * @param $reply_id
	 *            回复的是哪一条用户消息ID
	 */
	private void setFees(String fees) {
		// TODO Auto-generated method stub
		Utils.showPrgress(Mail245Activity.this);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("uid", Utils.getUid(Mail245Activity.this));
		map.put("zhaneniId", payUserContactShow1Model.getZhannei_Id());
		map.put("fees", fees);
		map.put("reply_id", payUserContactShow1Model.getContent_id());

		CommonUtils.CommomPostfunction(Mail245Activity.this,
				Constants.BadiUrl_1 + "/" + "inform/setFees", map, handler, 1,
				4, 2, 7);
	}

	private class ListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return payUserContactShow1Model.getZhannei_usercontact().size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub//title
			LayoutInflater inflater = LayoutInflater.from(Mail245Activity.this);
			View view = inflater.inflate(R.layout.mail_no_zhannei_item, null);
			TextView contents = (TextView) view
					.findViewById(R.id.zhannei_item_content);
//			   
			ImageView head = (ImageView) view.findViewById(R.id.head);
			TextView title = (TextView) view.findViewById(R.id.title);// 主旨
			TextView nickName = (TextView) view.findViewById(R.id.nickName);// 昵称
			GridView item_gridView = (GridView) view.findViewById(R.id.item);//
			TextView time = (TextView) view.findViewById(R.id.time);// 时间
			String type = "0";// 0.匿名 1，不匿名
			String is_sender = "1";// 1.问方，0答方
			String message_wenfang = "1";// 1.该条消息是问方发的，0答方发的
			// 时间
			if (!StringUtil.isNullOrEmpty(payUserContactShow1Model.getZhannei_usercontact().get(position).getTime())) {
				String bb=CalendarTools.getTimeChangeToString(Mail245Activity.this,
						payUserContactShow1Model.getZhannei_usercontact().get(position).getTime());
				time.setText(""+bb);
			} else {
				time.setText("");
			}

			if (payUserContactShow1Model.getIs_anonymity().equals("1")) {
				type = "0";
			} else {
				type = "1";
			}
			// 登录方是问方
			if (payUserContactShow1Model.getLoginUserRank().equals("asker")) {
				is_sender = "1";

			} else {
				is_sender = "0";
			}
			// 如果是该条消息的发送方
			// if
			// (payUserContactShow1Model.getZhannei_usercontact().get(position)
			// .getSender_rank().equals("asker")) {
			// message_wenfang = "1";
			// } else {
			// message_wenfang = "0";
			// }
			if (payUserContactShow1Model
					.getZhannei_usercontact()
					.get(position)
					.getSent_uid()
					.equals("" + payUserContactShow1Model.getReceiver().getId())) {
				message_wenfang = "0";
			} else {
				message_wenfang = "1";
			}
			// 获取所有的包含图片的<src= >类似的html语言
			List<String> list = null;

			if (payUserContactShow1Model.getZhannei_usercontact().get(position)
					.getContents() != null) {
				list = RegexUtils.getImgSrc(payUserContactShow1Model
						.getZhannei_usercontact().get(position).getContents());
				// for(int i=0;i<list.size();i++)
				// {
				// LogUtils.d("列表是：==》"+list.get(i).toString());
				// }

			}
			if (list != null && !list.isEmpty()) {
//				LogUtils.d("列表是：==》不是空");
				GridViewListAdapter adapter = new GridViewListAdapter(
						Mail245Activity.this, list);
				item_gridView.setAdapter(adapter);
				String aa = payUserContactShow1Model.getZhannei_usercontact()
						.get(position).getContents();

				List<String> listgroup = RegexUtils.getImgSrcGroup(aa);
				for (int i = 0; i < listgroup.size(); i++) {
					// "/Public/js/
					// <img src=' ' />
					if (listgroup.get(i)
							.indexOf(Constants.Fei_biaoqing_qianzui) != -1
							|| list.get(i).indexOf(
									Constants.Fei_biaoqing_qianzui2) != -1
							|| list.get(i).indexOf(
									Constants.Fei_biaoqing_qianzui3) != -1
							|| list.get(i).indexOf(
									Constants.Fei_biaoqing_qianzui4) != -1)
						aa = aa.replace(listgroup.get(i), "");// ("<img src='"+list.get(i)+"' />","");

				}
				new HtmlUtils(Mail245Activity.this, contents, aa)
						.showTextView();
//				LogUtils.d("aa=" + aa);
				// <img src=' '/ >

			} else if (list == null || list.isEmpty()) {
//				LogUtils.d("列表是：==》是空");
				new HtmlUtils(Mail245Activity.this, contents,
						payUserContactShow1Model.getZhannei_usercontact()
								.get(position).getContents()).showTextView();
			}
			title.setText(""+getResources().getString(R.string.keynote_)
					+ payUserContactShow1Model.getZhannei_usercontact()
							.get(position).getTitle());
			// 如果问方匿名，该条消息是问方发的
			if (type.equals("0") && message_wenfang.equals("1")
					&& !is_sender.equals("1")) {
				nickName.setText(getResources().getString(
						R.string.wx_Anonymous_user));
				ImageLoader.getInstance().displayImage(nimingHead, head,
						options);
			} else// 该条消息是问方发的,问方没有匿名
			{
				nickName.setText(""
						+ payUserContactShow1Model.getSender().getNickName());
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl
								+ "/"
								+ payUserContactShow1Model.getSender()
										.getHead() + Constants.appPhoto4img,
						head, options);
			}
			// 如果是答方发的
			if (message_wenfang.equals("0")) {
				nickName.setText(""
						+ payUserContactShow1Model.getReceiver().getNickName());
				ImageLoader.getInstance().displayImage(
						Constants.BadiDownImgUrl
								+ "/"
								+ payUserContactShow1Model.getReceiver()
										.getHead() + Constants.appPhoto4img,
						head, options);
			}

			return view;
		}

	}

	/**
	 * 删除站内信操作---POST
	 * 
	 * @param $uid
	 *            ---登录用户ID
	 * @param $zhanneiId
	 *            ----站内信ID
	 * @param $type
	 *            ----删除的站内信类型 zhannei_usercontact：用户联系 zhannei_clubnotice：俱乐部通知
	 *            zhannei_contactclub：联系俱乐部
	 * @param $rank
	 *            ---操作者的身份 asker：问方 answerer：答方 注意：当为“用户联系”才有该参数
	 */
	private void delete(String uid, String zhanneiId, String type, String rank,
			android.os.Handler handler) {
		Utils.showPrgress(Mail245Activity.this);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("uid", uid);
		map.put("zhanneiId", zhanneiId);
		map.put("type", type);
		if (type.equals("zhannei_usercontact")) {
			map.put("rank", rank);
		}
		CommonUtils.CommomPostfunction(Mail245Activity.this,
				Constants.BadiUrl_1 + "/" + "inform/delete", map, handler, 1,
				4, 5, 6);
	}

}
